<template>
  <div class="relative">
    <!-- 地图容器 -->
    <div ref="wrapRef" :style="{ height, width }"></div>
    <!-- 搜索条件 -->
    <div class="search-form z-999 absolute top-15px right-15px p-15px">
      <a-form layout="inline" :model="searchForm" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-form-item label="型号：">
          <JSearchSelect
            style="width: 200px;"
            placeholder="请选择型号"
            allowClear
            v-model:value="searchForm.type"
            :dictOptions="carTypeOptions"
            @change="getVinList"
          >
          </JSearchSelect>
        </a-form-item>
        <a-form-item label="VIN：">
          <JSearchSelect
            style="width: 200px;"
            placeholder="请选择VIN"
            allowClear
            v-model:value="searchForm.vin"
            :dictOptions="carVinOptions">
          </JSearchSelect>
        </a-form-item>
        <a-button type="primary" @click="onSearchVehicle">
          查询
        </a-button>
      </a-form>
    </div>
    <!-- 汽车详细信息 -->
    <div ref="carDataRef" class="w-100% color-#ded9d9 py-15px hidden ">
      <p>资产所属：{{carData.a}}</p>
      <p>车辆管理者：{{carData.b}}</p>
      <p>车型：{{carData.c}}</p>
      <p @click="handleCarInfo">VIN：<span style="color:#009DD9;cursor: pointer;">{{carData.d}}</span></p>
      <p>停放场所（一级）：A区试验区</p>
      <p>停放场所（二级）：A03</p>
      <p>駐車番地：2031</p>
      <p>车辆状态：检测中</p>
    </div>
  </div>
</template>
<script lang="ts" setup>
  import { ref, nextTick, unref, onMounted, reactive } from 'vue';
  import JSearchSelect from '/@/components/Form/src/jeecg/components/JSearchSelect.vue';
  import { uniqBy } from 'lodash-es';
  import markerIcon from "./u210.svg"
  import newMarkerIcon from "./u144.svg"
  import styleJson from "./map-style.json"
  defineProps({
    width: {
      type: String,
      default: '100%',
    },
    height: {
      type: String,
      default: 'calc(100vh - 78px)',
    },
  });
  const labelCol = reactive({
    xs: { span: 24 },
    sm: { span: 4 },
  });
  const wrapperCol = reactive({
    xs: { span: 24 },
    sm: { span: 20 },
  });
  // 搜索信息
  const searchForm = ref({
    vin:undefined,
    type:undefined
  });
  
  // 车辆列表
  const vehicleList = ref<object[]>([]);

  // 型号搜索列表，根据型号去重
  const carTypeOptions = ref<object[]>([]);

  // 根据型号获取车辆vin搜索列表
  const carVinOptions = ref();


  let map;
  const wrapRef = ref<HTMLDivElement | null>(null);
  const { BMapGL, BMapLib } = (window as any);
  
  // 设置信息弹窗
  const infoWindow = new BMapGL.InfoWindow("", { offset: new BMapGL.Size(110, 230), enableCloseOnClick:false });
  // 激活的标注
  let activeMarker;
  
  // 点击标注弹窗信息
  const carData = ref({});
  const carDataRef = ref();

  // 获取车辆列表
  function getVehicleList(){
    // 聚合点标注数组
    let markers = [];
    setTimeout(() => {
      vehicleList.value = [
        {id:0, lng: 117.179255, lat: 39.051298, a:"生管1", b:"管理者1", c:"Toyota Camry1", d:"WBABB1BK3DG000001" },
        {id:1, lng: 117.098767, lat: 39.014528, a:"生管2", b:"管理者2", c:"Toyota Camry2", d:"WBABB1BK3DG000002" },
        {id:2, lng: 117.091293, lat: 38.997033, a:"生管3", b:"管理者3", c:"Toyota Camry3", d:"WBABB1BK3DG000003" },
        {id:3, lng: 117.358054, lat: 39.133738, a:"生管4", b:"管理者4", c:"Toyota Camry4", d:"WBABB1BK3DG000004" },
        {id:2, lng: 117.318124, lat: 39.086261, a:"生管5", b:"管理者5", c:"Toyota Camry4", d:"WBABB1BK3DG000005" },
      ]
      carTypeOptions.value = uniqBy(vehicleList.value, item => item.c).map(item=>({text:item.c, value:item.c}))
      getVinList();
      // 向地图中添加标注
      vehicleList.value.forEach(item => {
        const { marker, point } = createMarker(item);
        markers.push(marker);
        item.marker = marker;
        marker.removeEventListener("click", handleChangeMarkerIcon);
        marker.addEventListener("click",  function () {
          marker.isClicked = !marker.isClicked;
          handleChangeMarkerIcon(marker, item);
        });
        // 将标注添加到地图中
        map.addOverlay(marker);                     
      });
      // new BMapLib.MarkerClusterer(map, {markers:markers});
    }, 2000);
  }

  // 初始化地图
  async function initMap() {
    await nextTick();
    const wrapEl = unref(wrapRef);
    if (!wrapEl) return;
    map = new BMapGL.Map(wrapEl);
    const centerPoint = new BMapGL.Point(117.179255, 39.051298);
    map.centerAndZoom(centerPoint, 10);
    map.enableScrollWheelZoom(true);
    // 设置地图样式
    map.setMapStyleV2({ styleJson });
  }
  // 创建地图中的标注
  function createMarker(item) {
    let point = new BMapGL.Point(item.lng, item.lat);   
    let marker = new BMapGL.Marker(point); 
    marker.isClicked = true;
    setDefaultMarkerltIcon(marker);   
    return { marker, point};
  }
  // 设置自定义点标注默认图标
  function setDefaultMarkerltIcon(marker){
    const defaultMarkerIcon = new BMapGL.Icon(markerIcon, new BMapGL.Size(26, 26));
    marker.setOffset(new BMapGL.Size(0, 0));
    marker.setIcon(defaultMarkerIcon);
  }
  // 设置自定义点标注激活图标
  function setActiveMarkerIcon(marker) {
    const activeMarkerIcon = new BMapGL.Icon(newMarkerIcon, new BMapGL.Size(38, 48));
    marker.setOffset(new BMapGL.Size(0, -13));
    marker.setIcon(activeMarkerIcon);
  }
  // 设置点击自定义标注更换图标
  function handleChangeMarkerIcon (marker, data?: any){
    // 改变上一个点击的标注的样式
    if ((activeMarker?.latLng?.lng == marker.latLng.lng) && (activeMarker?.latLng?.lat == marker.latLng.lat)) {
      activeMarker = null;
    }
    if(activeMarker){
      activeMarker.isClicked = true;
      setDefaultMarkerltIcon(activeMarker);
    }
    
    if (marker.isClicked) {
      setDefaultMarkerltIcon(marker);
      // 关闭信息窗
      marker.closeInfoWindow(infoWindow);
    } else {
      setActiveMarkerIcon(marker);
      // 设置信息弹窗内容
      carDataRef.value.style.display = "block";
      carData.value = data;
      infoWindow.setContent(carDataRef.value);
      // 打开信息窗口
      marker.openInfoWindow(infoWindow);
      activeMarker = marker;
    };
  }
  // 点击弹窗中的vin跳转到车辆详细信息
  function handleCarInfo() {
    console.log(carData.value);
  }

  // 根据型号获取vin
  function getVinList (data?:string){
    if (data) {
      carVinOptions.value = vehicleList.value.filter(item=>item.c == data).map(item=>({text:item.d, value:item.d, c:item.c}))
    }else{
      carVinOptions.value = vehicleList.value.map(item=>({text:item.d, value:item.d, c:item.c}));
    }
  }
  // 搜索车辆
  function onSearchVehicle () {
    const { vin, type } = searchForm.value;
    if (!vin && !type) {
      vehicleList.value.forEach(item=>{
        item.marker.isClicked = true;
        handleChangeMarkerIcon(item.marker, item);
      })
    }
    if (vin) {
      const vinSearch = vehicleList.value.find(item=>item.d == vin);
      if (vinSearch) {
        vinSearch.marker.isClicked = false;
        handleChangeMarkerIcon(vinSearch.marker, vinSearch);
      }
    } else if (type && !vin) {
      const typeSearch = vehicleList.value.filter(item=>item.c == type);
      typeSearch.forEach(item=>setActiveMarkerIcon(item.marker));
    }
  }
  onMounted(() => {
    initMap();
    getVehicleList();
  });

</script>
<style lang="less">
.BMap_bubble_pop{
  border:none !important;
  background-color: rgba(0, 0, 0, .8) !important;
  img, .BMap_bubble_top{
    display: none !important;
  }
}
</style>
<style lang="less" scoped>
  .search-form{
    background-color: rgba(255, 255, 255, .8)
  }
</style>
